#include "mma845x.h"

volatile uint8_t I2C_Status=0;
#define I2C_BUF_LEN           16
uint8_t I2C_Buf[I2C_BUF_LEN];

void mma845x_writereg(uint8_t reg_add, uint8_t reg_val)
{
    uint32_t    flags;
	uint8       I2C_Buffer[2];

	// set up the buffer and send (with stop sequence)
	I2C_Buffer[0] = reg_add;
	I2C_Buffer[1] = reg_val;
    
	if (I2C_SENSORS_I2CMasterWriteBuf(FXOS8700_I2C_ADDR, I2C_Buffer, 2, I2C_SENSORS_I2C_MODE_COMPLETE_XFER) != I2C_SENSORS_I2C_MSTR_NO_ERROR)
		return;	

	// idle until error or transmission complete 
    do {
	    flags = I2C_SENSORS_I2CMasterStatus();
        if ((flags & I2C_SENSORS_I2C_MSTAT_WR_CMPLT) & I2C_SENSORS_I2C_MSTAT_WR_CMPLT) 
        {
            I2C_SENSORS_I2CMasterClearStatus();
            break;
        }
    }while(1);

    I2C_SENSORS_I2CMasterClearStatus();
}

uint8_t mma845x_readreg(uint8_t reg_add)
{
    int i;
    int nbytes = 1;
    uint8 I2C_Buffer = 0;
    
    // Send "START"
    I2C_SENSORS_I2CMasterSendStart(FXOS8700_I2C_ADDR, I2C_SENSORS_I2C_WRITE_XFER_MODE);
    
    // Send I2CRegister
    I2C_SENSORS_I2CMasterWriteByte(reg_add);
    
    // Send "RESTART"
    I2C_SENSORS_I2CMasterSendRestart(FXOS8700_I2C_ADDR, I2C_SENSORS_I2C_READ_XFER_MODE);
    
    // Read desired bytes

    I2C_Buffer = I2C_SENSORS_I2CMasterReadByte(I2C_SENSORS_I2C_NAK_DATA);

    
    // Send "STOP"
    I2C_SENSORS_I2CMasterSendStop();

    I2C_SENSORS_I2CMasterClearStatus();

    return I2C_Buffer;
}

void mma845x_read_data(uint8 *g_value)
{
    int i;
    int nbytes = 6;
    
    
    // Send "START"
    I2C_SENSORS_I2CMasterSendStart(FXOS8700_I2C_ADDR, I2C_SENSORS_I2C_WRITE_XFER_MODE);
    
    // Send I2CRegister
    I2C_SENSORS_I2CMasterWriteByte(MMA845x_OUT_X_MSB);
    
    // Send "RESTART"
    I2C_SENSORS_I2CMasterSendRestart(FXOS8700_I2C_ADDR, I2C_SENSORS_I2C_READ_XFER_MODE);
    
    // Read desired bytes
    for (i=0; i<nbytes; i++)
    {
        if (i==(nbytes-1))
        {
            g_value[i] = I2C_SENSORS_I2CMasterReadByte(I2C_SENSORS_I2C_NAK_DATA);
        }
        else
        {
            g_value[i] = I2C_SENSORS_I2CMasterReadByte(I2C_SENSORS_I2C_ACK_DATA);
        }
    }
    
    // Send "STOP"
    I2C_SENSORS_I2CMasterSendStop();

    I2C_SENSORS_I2CMasterClearStatus();

    return;
}

